'use client';

import { useSingleton } from 'foxact/use-singleton';
import { createContext, useContext, useEffect } from 'react';
import { type Socket, io } from 'socket.io-client';

const SocketContext = createContext<null | Socket>(null);
export const useSocket = () => useContext(SocketContext);

export default function SocketProvider({
  children,
  appUrl,
}: {
  children?: React.ReactNode;
  appUrl: string;
}) {
  const socketClient = useSingleton(() => {
    return io(appUrl, {
      addTrailingSlash: false,
    });
  });

  useEffect(() => {
    const handler = () => socketClient.current?.disconnect();
    window.addEventListener('beforeunload', handler);
    window.addEventListener('unload', handler);
    return () => {
      window.removeEventListener('beforeunload', handler);
      window.removeEventListener('unload', handler);
    };
  }, [socketClient.current]);

  return <SocketContext value={socketClient.current}>{children}</SocketContext>;
}
